#!/bin/bash

function image_type
# args: $1 disk
{
  file $1 | awk '/x86 boot sector/ { print "raw" } /Qcow.*Version:.*2/ { print "qcow2" }'
}

function convert_to_raw
# args: $1 disk, $2 type
{
  ret=$1.raw
  qemu-img convert -f $2 $1 -O raw $ret
}

function mount_part1
# args: $1 disk
{
  offset_p1=32256       #FIXME this is ugly
  loopdev=$(losetup -f) #FIXME potential race condition here
  losetup -o $offset_p1 $loopdev $1
  losetup $loopdev
  ret=$(mktemp -d)
  mount $loopdev $ret -t vfat -o shortname=winnt
}

function cleanup
# args: $1 mountdir
{
  echo umount $1
  umount $1
  rmdir $1
  echo free $loopdev
  losetup -d $loopdev
}

function save_archive
# args: $1 dir_to_save, $2 outfile_prefix
{
  ## dump attributes
  $topdir/dosfs_attrib.py $1 dump > $1/attributes.dump
  ## tar.gz
  ret=$2.tar.gz
  tar cvzf $ret -C $1 -X $topdir/windows_exclude.conf .

  ## tar.bz2
  #ret=$2.tar.bz2
  #tar cvjf $ret -C $1 -X $topdir/windows_exclude.conf .

  ## 7z
  #ret=$2.7z
  #cwd=$PWD
  #cd $1
  #7zr a -x@$topdir/windows_exclude.conf $cwd/$ret
  #cd $cwd
}

topdir=$(dirname $0)
if [ $(expr substr $topdir 1 1) != / ] ; then
  topdir=$PWD/$topdir
fi

# show usage
if [ x$1 == x ] ; then
  echo Usage: $0 source_vm_disk
  exit 1
fi

# get source image type
srcdisk=$1
echo -n "identify $srcdisk type: "
srctype=$(image_type $srcdisk)
echo $srctype

# try convert to raw first
if [ x$srctype != xraw ] ; then
  convert_to_raw $srcdisk $srctype
  srcdisk=$ret
fi

# test if convert success
srctype=$(image_type $srcdisk)
if [ x$srctype != xraw ] ; then
  echo error, disk $srcdisk not converted to raw
  exit 1
fi

# try to mount first partition
mount_part1 $srcdisk
srcdir=$ret

# set trap to free mount and loopdev
trap "test -e $srcdir && cleanup $srcdir" INT TERM EXIT

# save archive -- take loooong
outfile_prefix=$(basename $srcdisk .raw)
save_archive $srcdir $outfile_prefix
outfile=$ret
echo windows extracted to archive: $outfile
